from PyQt5.QtWidgets import *
from PyQt5 import QtGui
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import time
import pymysql
import pickle

import interface.student.select_course as select_course
import database.admin.setting as setting
import interface.student.yiyuanzhi as yiyuanzhi
import interface.student.stu_main0_Window as stu_main0_Window
import pickle
class yyz(QMainWindow,yiyuanzhi.Ui_Dialog):
    def __init__(self,cid,sid,term):
        QMainWindow.__init__(self)
        yiyuanzhi.Ui_Dialog.__init__(self)
        self.setupUi(self)
        self.setWindowTitle("选课")
        self.cancel.clicked.connect(self.close)
        self.ok.clicked.connect(self.commit)
        self.sid=sid
        self.cid=cid
        self.term=term
    def check(self):
        self.connect = pymysql.connect(**setting.config)
        self.cursor = self.connect.cursor()
        sql_2 = "select * from history_sc where sid=%s and cid=%s"
        self.cursor.execute(sql_2, (self.sid, self.cid))
        re = self.cursor.fetchall()
        if (len(re)!= 0):
            QMessageBox.warning(self, "错误", "你已修读过该课程!")
            return False
        sql_2 = "select * from select_course_state  where sid=%s and cid=%s and time=%s and status=1"
        self.cursor.execute(sql_2, (self.sid, self.cid,self.term))
        now=self.cursor.fetchall()
        if (len(now)!= 0):
            QMessageBox.warning(self, "错误", "你本学期已选该课程!")
            return False
        sql_="select c1.credit from course c1 where c1.id=%s"
        self.cursor.execute(sql_,self.cid)
        c=self.cursor.fetchone()
        self.credit=c[0]
        sql_="select c1.pre_id,c1.credit,c2.cname from course c1,course c2 where c1.id=%s and c1.pre_id=c2.id"
        self.cursor.execute(sql_,self.cid)
        re = self.cursor.fetchall()
        if(len(re)!=0):
            self.pre_id=re[0][0]
            self.credit=re[0][1]
            self.pre_name=re[0][2]
            sql_1="select * from history_sc where sid=%s and cid=%s"
            self.cursor.execute(sql_1,(self.sid,self.pre_id))
            re2=self.cursor.fetchall()
            if(len(re2)==0):
                QMessageBox.warning(self,"错误","请先修读课程:"+self.pre_name)
                return False
        sql_3="select credit_up,now_credit,value from stu_cv where sid=%s "
        self.cursor.execute(sql_3,self.sid)
        re3=self.cursor.fetchone()
        credit_up=re3[0]
        now_credit=re3[1]
        now_value=re3[2]
        v=int(self.money.text())
        self.v=v
        if(now_value-v<0):
            QMessageBox.warning(self,"错误","意愿值不足")
            return False
        if(now_credit+self.credit>credit_up):
            QMessageBox.warning(self,"错误","学分超限")
            return False
        sql_="select volume,stus from course_schedule  where cid=%s and year_time=%s "
        self.cursor.execute(sql_,(self.cid,self.term))
        re=self.cursor.fetchone()
        #if(re[1]+1>re[0]):
        #    QMessageBox.warning(self,"错误","该课程已被选满")
        #    return False
        #######查看是否有时间上冲突的课程
        sql_="select cs.w1,cs.w2,cs.c1,cs.c2,cs.day from course_schedule cs where cs.cid=%s and cs.year_time=%s "
        args=(self.cid,self.term)
        self.cursor.execute(sql_,args)
        res=self.cursor.fetchone()
        print(res)
        sql_ = "select c.cname,cs.w1,cs.w2,cs.c1,cs.c2,cs.day from select_course_state s ,course_schedule cs ,course c where s.sid=%s and s.time=%s and cs.year_time=%s \
               and s.status=1 and s.cid=cs.cid and c.id=s.cid"
        arg=(self.sid,self.term,self.term)
        self.cursor.execute(sql_,arg)
        res_other=self.cursor.fetchall()
        print(res_other)
        if(len(res_other)!=0):
            now_bw=res[0]
            now_ew=res[1]
            now_bc=res[2]
            now_ec=res[3]
            now_day=list(res[4])
            info=(now_bw,now_ew,now_bc,now_ec,now_day)
            print(info)
            for i in range(len(res_other)):
                t_n=res_other[i][0]
                t_bw=res_other[i][1]
                t_ew=res_other[i][2]
                t_bc=res_other[i][3]
                t_ec=res_other[i][4]
                t_day=list(res_other[i][5])
                if(t_ew<now_bw or now_ew<t_bw):
                    continue
                else:
                    temp=[k for k in now_day in k in t_day]
                    if(len(temp)==0):
                        continue
                    else:
                        if(now_bc==t_bc or now_ec==t_ec):
                            QMessageBox.warning(self,"错误","该课程与已选的"+t_n+"时间冲突")
                            return False
        #######
        return True
    def commit(self):
        if(self.money.text()):
            QMessageBox.warning(self,"错误","请投入意愿值")
        else:
            if(self.check()):
                self.connect = pymysql.connect(**setting.config)
                self.cursor = self.connect.cursor()
                try:
                    sql_="Insert into select_course_state values(%s,%s,%s,%s,%s)"
                    self.cursor.execute(sql_,(self.cid,self.sid,self.term,self.v,1))
                    sql_="update stu_cv set value=value-%s,now_credit=now_credit+%s where sid=%s and time =%s "
                    self.cursor.execute(sql_,((self.v),(self.credit),self.sid,self.term))
                    sql_="update course_schedule set stus=stus +1 where cid=%s and year_time=%s "
                    self.cursor.execute(sql_, (self.cid, self.term))
                    self.connect.commit()
                except:
                    self.connect.rollback()
                self.cursor.close()
                self.connect.close()
                QMessageBox.information(self,"提示","选课成功！")
                self.close()


class select_course_window(QMainWindow,select_course.Ui_Form):
    def __init__(self,sid):
        QMainWindow.__init__(self)
        select_course.Ui_Form.__init__(self)
        self.setupUi(self)
        self.setWindowTitle("学生选课界面")
        #self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.table.setColumnCount(10)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        #self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        #self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        # self.table.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
       # self.table.verticalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.table.setHorizontalHeaderLabels(['课程号', '课程名', '学分', '授课老师', '教材','先修课','课程时间','课容量','已选', '选择'])
        self.credit_box.addItem('ALL')
        self.credit_box.addItem('0.5')
        self.credit_box.addItem('1')
        self.credit_box.addItem('1.5')
        self.credit_box.addItem('2')
        self.credit_box.addItem('2.5')
        self.credit_box.addItem('3')
        self.credit_box.addItem('3.5')
        self.credit_box.addItem('4')
        self.credit_box.addItem('4.5')
        self.teacher_box.addItem('ALL')
        self.r_all.setChecked(True)
        self.quit_.clicked.connect(self.close)
        self.sid=sid#学生id
        self.read()
        self.init_table()
        #self.read()
        #self.select()
        self.back.clicked.connect(self.load_pre)
        timer = QTimer(self)
        timer.timeout.connect(self.showtime)
        timer.start()
    def read(self):
        with open("admin/time.pkl",'rb') as f:
            begin=pickle.load(f)
            end=pickle.load(f)
            term=pickle.load(f)
        self.end=end
        print(begin,end)
        self.term=term
        self.now_term.setText(self.term)
    def showtime(self):
        now= QDateTime.currentDateTime()
        end = self.end
        time=(now.msecsTo(end)/float(1000))
        #print(time)
        day=(((time/60)/60)/24)
        day=int(day)
        hours=(((time-day*24*60*60)/3600))
        hours=int(hours)
        min=((time-day*24*60*60-hours*60*60)/60)
        min=int(min)
        sec=(time-day*24*60*60-hours*60*60-min*60)
        #print(day,hours,min,sec)

        text ="{}天{}小时{}分钟{}秒".format(int(day),int(hours),int(min),int(sec))
        #print((text))
        self.time.setText(text)
    def load_pre(self):
        self.pre=stu_main0_Window.stu_main0_window(self.sid)
        self.pre.show()
        self.close()
    def init_table(self):
        self.connect = pymysql.connect(**setting.config)
        self.cursor = self.connect.cursor()
        sql_="select * from course where exists (select * from course_schedule c where c.cid=course.id)"
        self.cursor.execute(sql_)
        res=self.cursor.fetchall()
        self.display_find_result(res)
        sql_="select value,now_credit from stu_cv where sid=%s "
        self.cursor.execute(sql_,self.sid)
        re=self.cursor.fetchone()
        self.money.setText(str(re[0]))
        self.credit.setText(str(re[1])+'学分')
        sql_="select name from teachers "
        self.cursor.execute(sql_)
        re=self.cursor.fetchall()
        for i in range(len(re)):
            self.teacher_box.addItem(re[i][0])
        self.cursor.close()
        self.connect.close()
    def sh(self):
        self.close()
        self.init_table()
        self.show()
    def sel_but(self,cid,sid):
        widget=QWidget()
        sel=QPushButton("选课")
        q=yyz(cid,sid,self.term)
        def load_():
            # `>?print("Yes")
            #QMessageBox.about(self, "提示", "是否选课")
            q.show()
            q.ok.clicked.connect(self.sh)
        #hLayout=QHBoxLayout()
       # hLayout.addWidget(sel)
        #widget.setLayout(hLayout)
        sel.clicked.connect(load_)
        return sel
    def display_find_result(self,re):
        self.table.setRowCount(0)
        row=self.table.rowCount()
        #self.table.setRowCount(row+1)
        re_len=len(re)
        #print(re[2])
        for l in range(re_len):
            #print(l)
            row = self.table.rowCount()
            self.table.setRowCount(row + 1)
            #ck=QCheckBox()
            #h=QHBoxLayout()
            #h.setAlignment(Qt.AlignCenter)
            #h.addWidget(ck)
            #w=QWidget()
            #w.setLayout(h)
            check=QtWidgets.QTableWidgetItem()
            check.setCheckState(QtCore.Qt.Unchecked)
            #self.table.setHorizontalHeaderLabels(['课程号', '课程名', '学分', '授课老师', '教材','先修课', '选择'])
            #print(type(re))
            self.table.setItem(row,0,QTableWidgetItem(re[l][0]))
            self.table.setItem(row, 1, QTableWidgetItem(re[l][1]))
            self.table.setItem(row, 2, QTableWidgetItem(str(re[l][2])))
            self.table.setItem(row, 3, QTableWidgetItem(re[l][4]))
            self.table.setItem(row, 4, QTableWidgetItem(re[l][5]))
            self.table.setItem(row, 5, QTableWidgetItem('无'))
            pid=re[l][6]
            #print(pid)
            if(pid!=None):
                sql_="select cname from course where id=%s"
                self.cursor.execute(sql_,pid)
                res=self.cursor.fetchone()
                self.table.setItem(row, 5, QTableWidgetItem(res[0]))
            sel=self.sel_but(re[l][0],self.sid)
            #sel.setDown(True)
            #self.table.setItem(row,6,check)
            sql_="select week_time,day_time,class_time,volume,stus from course_schedule where cid=%s"
            self.cursor.execute(sql_,re[l][0])
            res=self.cursor.fetchone()
            self.table.setItem(row,6,QTableWidgetItem(res[0]+';'+res[1]+';'+res[2]))
            self.table.setItem(row,7,QTableWidgetItem(str(res[3])))
            self.table.setItem(row,8,QTableWidgetItem(str(res[4])))
            self.table.setCellWidget(row,9,sel)
            #self.table.setCellWidget(row, 5,w)
        #self.select()
if __name__=='__main__':
    app=QApplication(sys.argv)
    md=select_course_window('2018300355')
    md.show()
    sys.exit(app.exec_())